﻿namespace Quail.Helpers
{
    /// <summary>
    /// Provides a thread-safe boolean flag
    /// </summary>
    public class LimitedUseFlag
    {
        private readonly object _syncLock = new object();
        private readonly int _maxuses;
        private int _numberofuses;

        /// <summary>
        /// Initializes a new instance of the <see cref="LimitedUseFlag"/> class.
        /// </summary>
        /// <param name="numberofuses">The number of uses for this flag.</param>
        public LimitedUseFlag(int numberofuses)
        {
            _maxuses = numberofuses;
            _numberofuses = numberofuses;
            
        }

        /// <summary>
        /// Gets the maximum number of times a flag can be used
        /// </summary>
        public int FlagMaxUsage
        {
            get
            {
                return _maxuses;
            }
        }

        /// <summary>
        /// Attempts to use the flag.  This method returns TRUE only up to FlagMaxUsage times.
        /// </summary>
        /// <returns>True if the flag can be used</returns>
        public bool AttemptToUseFlag()
        {
            lock(_syncLock)
            {
                if (_numberofuses == 0)
                    return false;

                _numberofuses--;

                return true;
            }
        }
    }
}
